﻿using SSCMS.Parse;
using SSCMS.Plugins;
using SSCMS.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WF.BeOnDuty.BeOnDuty;
using WF.BeOnDuty.Models;

namespace WF.BeOnDuty.Stl
{
    public class StlDutyInfos : IPluginParseAsync
    {
        public string ElementName => "stl:wfDutys";
        private const string AttributeCount = "count";
        private readonly IDutyInfoRepository _repository;
        public StlDutyInfos(IDutyInfoRepository dutyInfoRepository) 
        {
            _repository = dutyInfoRepository;
        }

        public async Task<string> ParseAsync(IParseStlContext context)
        {
            int count = 7;

            foreach (var name in context.StlAttributes.AllKeys)
            {
                var value = context.StlAttributes[name];

                if (StringUtils.EqualsIgnoreCase(name, AttributeCount))
                {
                    count = TranslateUtils.ToInt(value);
                }
            }
            var list = await _repository.GetToDayCountAsync(context.SiteId, count);
            return  await ParseImplAsync(list,context);
        }
   
        private async Task<string> ParseImplAsync(IEnumerable<DutyInfo> models, IParseStlContext context)
        {
            var parsedContent = string.Empty;

            var itemIndex = 1;
            foreach (var item in models)
            {
                SetContextItem(context, item, itemIndex++);
                parsedContent += await context.ParseAsync(context.StlInnerHtml);
            }

            return parsedContent;
        }
        public  void SetContextItem(IParseContext context, DutyInfo duty, int itemIndex)
        {
            context.Set($"{nameof(DutyInfo)}:duty", duty);
            context.Set($"{nameof(DutyInfo)}:itemIndex", itemIndex);
        }
    }
}
